package kr.ac.kaist.simplefileexplorer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

public class GoogleDriveFileListActivity extends Activity {



 private static final int SEND_REQUEST_SUCCEED = 1;
 private static final int SEND_REQUEST_FAILED = 2; 
 private static final int REQUEST_AUTHORIZATION = 3;
 
 private static Uri fileUri;
 private static Drive service;

 private static String filename;
 private GoogleAccountCredential credential;

 
 ProgressDialog dialog;
 ProgressHandler handler;
 
 List<File> file_list;
 private ListView listViewRest;
 
 Context ctx;

 @Override
 public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_general_list);
	  
	ctx = this;
	  
	file_list = new ArrayList<File>();
	  
	handler = new ProgressHandler(); 
	
	Intent intent = getIntent();
	String accountName = intent.getExtras().getString("AccountName");
	credential = GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE_FILE));
	
	credential.setSelectedAccountName(accountName);
	service = getDriveService(credential);  
	
	try { 
		retrieveAllFiles(service);      		
	} catch (IOException e) {  
   // TODO Auto-generated catch block      e.printStackTrace();
	}	
	showWaitingPopUp();
 }



 private Drive getDriveService(GoogleAccountCredential credential) {
  return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
    new GsonFactory(), credential).build();
 }
 
 public void showToast(final String toast) {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    Toast.makeText(getApplicationContext(), toast,
      Toast.LENGTH_SHORT).show();
   }
  });
 }
 
 private void retrieveAllFiles(Drive service) throws IOException {
     final Files.List request = service.files().list();
     Thread t = new Thread(new Runnable() {
   @Override
   public void run() {   

        do {
          try {
           Log.v("","##@@  2");
            FileList files = request.execute();
            Log.v("","##@@  3");
            file_list.addAll(files.getItems());
            Log.v("","##@@  4");
            request.setPageToken(files.getNextPageToken());
            Log.v("","##@@  5");
          }catch (UserRecoverableAuthIOException e){
              System.out.println("An error occurred: " + e);
        	  startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
          } catch (IOException e) {
              System.out.println("An error occurred: " + e);
              request.setPageToken(null);
          }
        } while (request.getPageToken() != null &&
                 request.getPageToken().length() > 0);
        Log.v("","##@@  6");
        for(int i=0;i<file_list.size();i++){
         
         Log.v("","##@@ FileName : "+file_list.get(i).getTitle().toString()+"  ID : "+file_list.get(i).getId().toString());
         
        }
        	   
 	   Message msg = handler.obtainMessage();     
 	   
		msg.what = SEND_REQUEST_SUCCEED;
		String hi = new String("Query Done");
		msg.obj = hi;
		
		handler.sendMessage(msg); 	   
   }
  });
  t.start();

   }
 
 
 protected void showWaitingPopUp(){
 	dialog = new ProgressDialog(this);
		dialog.setTitle("Wait...");
		dialog.setMessage("Please wait while querying...");
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();	
 }
 
 protected void removeWaitingPopup(){
 	dialog.dismiss();
 }
 
 void updateFileList(){
	listViewRest = (ListView)findViewById(R.id.general_list_listv); 
	listViewRest.setAdapter(new GoogleFileListAdapter(ctx, R.layout.file_item, file_list));
     
	listViewRest.setOnItemClickListener(new OnItemClickListener() {
	      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              Intent intent = new Intent();
              intent.putExtra("FileName", file_list.get(position).getTitle().toString());
              intent.putExtra("FileId", file_list.get(position).getId().toString());
              setResult(RESULT_OK, intent);
              finish();
	      }
	});	    
 }
 
 public class ProgressHandler extends Handler{
 	public void handleMessage(Message msg){
 		
 		super.handleMessage(msg);
 		
 		switch(msg.what)
 		{
 			case SEND_REQUEST_SUCCEED:
 				//request done. update ui
 				removeWaitingPopup();
 				updateFileList();
 			break;
 			case SEND_REQUEST_FAILED:
 				//request failed. update ui
 				removeWaitingPopup(); 	   	
 				updateFileList();
 			break;   			
 			default:
 			break;
 		}
 		
 	}
 } 
}
